<template>
  <div class="left">
    <div class="price-type">{{ $t('限价卖出') }}</div>
    <div>
      <div class="limit-price-input">
        <span
          class="minus"
          @click="clickPriceMinus"
        ><i class="iconfont icon-minus" /></span>
        <input
          v-if="lockedPrice"
          v-model="price"
          type="text"
          class="number"
        />
        <input
          v-else
          type="text"
          class="number"
          :value="dynamicPrice | numberFormat()"
          @focus="lockPrice(dynamicPrice)"
        />
        <span
          class="plus"
          @click="clickPricePlus"
        ><i class="iconfont icon-plus" /></span>
      </div>
      <div class="cash-value">{{ $t('估值') }}：{{ currency.symbol }} {{ referenceValue | numberFormat() }}</div>
    </div>
    <div>
      <div class="limit-price-input">
        <span
          class="minus"
          @click="clickAmountMinus"
        ><i class="iconfont icon-minus" /></span>
        <input
          v-model="amount"
          type="text"
          class="number"
          :placeholder="`${$t('数量')}（${coinPair.stock}）`"
        />
        <span
          class="plus"
          @click="clickAmountPlus"
        ><i class="iconfont icon-plus" /></span>
      </div>
      <div class="rate-wrap">
        <div
          class="btn-rate"
          @click="pickAmountRatio(0.25)"
        >25%</div>
        <div
          class="btn-rate"
          @click="pickAmountRatio(0.5)"
        >50%</div>
        <div
          class="btn-rate"
          @click="pickAmountRatio(0.75)"
        >75%</div>
        <div
          class="btn-rate"
          @click="pickAmountRatio(1)"
        >100%</div>
      </div>
      <div class="amount-wrap">
        <div class="btn-amount">{{ $t('成交金额') }} {{ totalPrice > 0 ? totalPrice : '0.00' }} {{ coinPair.money }}</div>
      </div>
    </div>
    <div
      v-if="loggedIn"
      class="trade-wrap"
    >
      <div
        class="btn-trade btn-trade-sell"
        :class="{disabled: loading}"
        @click="handleOrder"
      >{{ $t('卖出') }}</div>
    </div>
    <div
      v-else
      class="trade-wrap"
    >
      <nuxt-link to="/login">
        <div class="btn-trade btn-login">{{ $t('登录/注册') }}</div>
      </nuxt-link>
    </div>
  </div>
</template>
<script>
import { mapState, mapGetters, mapActions } from 'vuex'
import loadBalance from './mixins/loadBalance'
import * as number from '@/utils/number'
import { USD } from '@/constants/global'
const side = 1 // 1: 卖出 2：买入
export default {
  mixins: [loadBalance],
  data () {
    return {
      loading: false,

      lockedPrice: false,
      price: 0,

      amount: '',
      errMsg: ''
    }
  },
  computed: {
    ...mapState({
      currency: ({ currency }) => currency,
      usd2cny: ({ market }) => market.usd2cny,
      realTimeDepth: ({ exchange }) => exchange.realTimeDepth,
      ownedCoins: ({ fund }) => fund.ownedCoins
    }),
    ...mapGetters({
      coinPair: 'market/coinPair',
      discountRate: 'market/discountRate'
    }),
    dynamicPrice () {
      if (this.realTimeDepth && this.realTimeDepth[this.symbol]) {
        return this.realTimeDepth[this.symbol].bids.length > 0
          ? this.realTimeDepth[this.symbol].bids[0][0] : 0
      }
      return 0
    },
    referenceValue () {
      if (this.currency.name === USD) {
        return this.realPrice * this.discountRate
      }
      return this.realPrice * this.discountRate * this.usd2cny
    },
    realPrice () {
      if (this.lockedPrice) {
        return Number.parseFloat(this.price)
      }
      return Number.parseFloat(this.dynamicPrice)
    },
    totalPrice () {
      return number.format(this.realPrice * this.amount)
    },
    totalAmount () {
      return this.ownedCoins[this.coinPair.stock]
        ? this.ownedCoins[this.coinPair.stock].available : 0
    }
  },
  methods: {
    ...mapActions({
      createOrder: 'exchange/createOrder'
    }),
    handleOrder () {
      if (this.loading) { return }
      do {
        if (this.realPrice <= 0 || this.amount <= 0) {
          this.errMsg = this.$t('价格或数量未填写')
          break
        }
        // TODO: param validate
      } while (false)
      if (this.errMsg) {
        this.$toast.error(this.errMsg)
        this.errMsg = ''
        return
      }
      this.lockPrice(this.dynamicPrice)
      this.$toast.show(`${this.$t('您确定要以')}${this.realPrice}${this.coinPair.money}${this.$t('价格卖出')}${this.amount}${this.coinPair.stock}`, {
        action: {
          text: this.$t('确定'),
          onClick: (e, toastObject) => {
            const payload = {
              side,
              market: this.symbol,
              pride: this.realPrice,
              amount: this.amount
            }
            const succeed = () => {
              this.loading = false
              this.loadBalance()
              this.$toast.success(this.$t('下单成功'))
            }
            const failed = (err) => {
              this.loading = false
              this.$toast.error(err.message)
            }
            this.loading = true
            this.createOrder(payload)
              .then(succeed)
              .catch(failed)
          }
        },
        duration: 6000
      })
    },
    pickAmountRatio (ratio) {
      this.amount = number.format2(this.totalAmount * ratio)
    },
    lockPrice (price) {
      if (this.lockedPrice) { return }
      this.lockedPrice = true
      this.price = number.format(price)
    },
    setPrice (price) {
      this.lockedPrice = true
      this.price = number.format(price)
    },
    clickPriceMinus () {
      this.lockPrice(this.dynamicPrice)
      if (this.price > 0.1) {
        this.price = number.format(this.realPrice * 1 - 0.1)
      }
    },
    clickPricePlus () {
      this.lockPrice(this.dynamicPrice)
      this.price = number.format(this.realPrice * 1 + 0.1)
    },
    clickAmountMinus () {
      if (this.amount > 0.1) {
        this.amount = number.format(this.amount * 1 - 0.1)
      }
    },
    clickAmountPlus () {
      this.amount = number.format(this.amount * 1 + 0.1)
    }
  }
}
</script>
<style scoped>
.price-type {
  font-size: 12px;
  line-height: 40px;
}
.limit-price-input {
  display: flex;
  border: 1px solid #eee;
  border-radius: 2px;
}
.limit-price-input .minus,
.limit-price-input .plus {
  width: 36px;
  height: 36px;
  line-height: 36px;
  text-align: center;
  background-color: #e8e6e6;
}
.limit-price-input .minus {
  border-right: 1px solid #eee;
}
.limit-price-input .plus {
  border-left: 1px solid #eee;
}
.limit-price-input .number {
  min-width: 100px;
  height: 36px;
  padding-left: 4px;
  font-size: 12px;
  background-color: #f7f4f4;
  flex: 1;
  text-align: center;
}
.cash-value {
  line-height: 36px;
}
.rate-wrap {
  margin-top: 10px;
  display: flex;
}
.btn-rate {
  flex: 1;
  height: 26px;
  line-height: 26px;
  border: 1px solid #ddd;
  text-align: center;
  font-size: 12px;
  color: black;
}
.btn-rate + .btn-rate {
  margin-left: 4px;
}
.amount-wrap {
  margin-top: 10px;
}
.btn-amount {
  background-color: #f7f4f4;
  height: 36px;
  line-height: 36px;
  text-align: center;
  color: #666;
}
.trade-wrap {
  margin-top: 10px;
}
.btn-trade {
  height: 36px;
  line-height: 36px;
  text-align: center;
  border-radius: 0px;
  color: white;
  font-size: 14px;
}
.btn-trade-sell {
  background-color: #d14b64;
}
.btn-trade-sell.disabled {
  opacity: 0.8;
}
.btn-login {
  background-color: #03a3fc;
}
</style>
